<template>
	<view class="out">
		<checkbox-group @change="itemChange">
			<view class="item" v-for="(item, index) in goods" :key="item.id">
				<checkbox :value="item.id" :checked="item.checked"></checkbox>
				<text class="title">{{item.name}}</text>
				<text class="price">{{item.price}}元</text>
				<text class="del" @click="remove(index)">删除</text>
			</view>
		</checkbox-group>
		
		<view class="card">
			<view class="text">选中{{totalNumber}}个产品，总价：{{totalPrice}}元</view>
		</view>
	</view>
</template>

<script setup>
import { computed, ref } from 'vue';

const goods = ref([
	{id:"11",name:"小米",price:4999,checked:false},
	{id:"22",name:"华为",price:6899,checked:false},
	{id:"33",name:"oppo",price:2989,checked:false},
	{id:"44",name:"苹果",price:9998,checked:false},
])

const remove = (index) => {
	console.log("下标为", index)
	goods.value.splice(index, 1)
}

// 选中的所有项
const selectGroup = ref([])

// 计算属性，计算所有选中商品的总数
const totalNumber = computed(() => {
	return selectGroup.value.length
})
// 计算属性，计算所有选中商品的总价
const totalPrice = computed(() => {
	return goods.value.filter(item => item.checked).reduce((prev,curr) => prev + curr.price, 0)
})

// 多选框，e.detail.value中包含选中的项
const itemChange = (e) => {
	selectGroup.value = e.detail.value
	goods.value.forEach(item => {
		item.checked = selectGroup.value.includes(item.id)
	})
}
</script>

<style scoped lang="scss">
.out{
	padding: 10px;
	.item{
		padding: 10px 0;
		.price{
			margin-left: 30px;
		}
		.del{
			color: red;
			margin-left: 30px;
		}
	}
	.card{
		margin-top: 30px;
		border: 1px solid #eee;
		padding: 10px 0;
	}
}
</style>
